package cn.iocoder.yudao.module.iot.gateway.protocol.tcp.router.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 协议处理器注册中心
 */
@Slf4j
@Component
public class ProtocolHandlerRegistry {
    private final Map<String, Map<String, ProtocolHandler>> handlers = new ConcurrentHashMap<>();

    @Autowired
    public ProtocolHandlerRegistry(List<ProtocolHandler> protocolHandlers) {
        // 自动注册所有ProtocolHandler
        for (ProtocolHandler handler : protocolHandlers) {
            registerHandler(handler);
        }
        log.info("[ProtocolHandlerRegistry] 已注册 {} 个协议处理器", protocolHandlers.size());
    }

    private void registerHandler(ProtocolHandler handler) {
        String protocolType = handler.getProtocolType();
        String handlerType = handler.getHandlerType();

        handlers.computeIfAbsent(protocolType, k -> new ConcurrentHashMap<>())
                .put(handlerType, handler);

        log.debug("[registerHandler] 注册协议处理器: protocol={}, handler={}", protocolType, handlerType);
    }

    /**
     * 获取指定协议和处理器类型的处理器
     * @param protocolType 协议类型
     * @param handlerType 处理器类型 (auth/business)
     * @return 协议处理器，未找到返回null
     */
    public ProtocolHandler getHandler(String protocolType, String handlerType) {
        Map<String, ProtocolHandler> protocolHandlers = handlers.get(protocolType);
        return protocolHandlers != null ? protocolHandlers.get(handlerType) : null;
    }

    /**
     * 获取默认处理器
     * @param handlerType 处理器类型
     * @return 默认协议处理器
     */
    public ProtocolHandler getDefaultHandler(String handlerType) {
        return getHandler("default", handlerType);
    }

    /**
     * 检查是否存在指定的协议处理器
     * @param protocolType 协议类型
     * @param handlerType 处理器类型
     * @return 是否存在
     */
    public boolean hasHandler(String protocolType, String handlerType) {
        return getHandler(protocolType, handlerType) != null;
    }
}
